﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using StudentInfo.Areas.StudentArea.Services;
using StudentInfo.Areas.StudentArea.ViewModelHelpers;
using StudentInfo.Areas.StudentArea.ViewModels;

namespace StudentInfo.Areas.StudentArea.Controllers
{
    public class StudentController : Controller
    {
        public ActionResult Index()
        {
            var students = StudentViewModelHelper.PopulateStudentViewModelList(StudentService.GetAll().ToList());
            return View(students);
        }

        public ActionResult Details(int studentId)
        {
            var s = StudentService.Get(studentId);
            var z = s.Marks;

            var student = StudentService.Get(studentId);

            if (student != null)
                return View(StudentViewModelHelper.PopulateStudentViewModel(student));

            return RedirectToRoute("Student", new { action = "Index" });
        }

        public ActionResult Edit(int studentId)
        {
            var student = StudentService.Get(studentId);

            if (student != null)
                return View(StudentViewModelHelper.PopulateStudentViewModel(student));

            return RedirectToRoute("Student", new { action = "Index" });
        }

        [HttpPost]
        public ActionResult Edit(StudentViewModel model)
        {
            var student = StudentViewModelHelper.PopulateStudentFromViewModel(model);

            if (student != null)
                StudentService.Save(student);

            return RedirectToRoute("Student", new { action = "Details", studentId = model.Id });
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(StudentViewModel model)
        {
            var student = StudentViewModelHelper.PopulateStudentFromViewModel(model);

            if (student != null)
                StudentService.Create(student);

            return RedirectToRoute("Student", new { action = "Index" });
        }

        public ActionResult Delete(int studentId)
        {
            var student = StudentService.Get(studentId);

            if (student != null)
                return View(StudentViewModelHelper.PopulateStudentViewModel(student));

            return RedirectToRoute("Student", new { action = "Index" });
        }


        [HttpPost]
        public RedirectToRouteResult Delete(int studentId, FormCollection collection)
        {
            var student = StudentService.Get(studentId);

            if (student != null)
                StudentService.Delete(student);

            return RedirectToRoute("Student", new { action = "Index" });
        }
    }
}
